<template>
  <div class="page-content">
    <el-form-item label="请求地址">
      <el-input v-model="apiPath"></el-input>
    </el-form-item>

    <el-form :model="secret">
      <el-form-item label="app_id">
        <el-input v-model="secret.app_id"></el-input>
      </el-form-item>
      <el-form-item label="app_secret">
        <el-input v-model="secret.app_secret"></el-input>
      </el-form-item>
      <el-form-item label="aes_key">
        <el-input v-model="secret.aes_key"></el-input>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="测试任务完成通知">
        <el-form :model="taskFinishForm">
          <el-form-item label="任务编码" prop="taskCode">
            <el-input v-model="taskFinishForm.taskCode"></el-input>
          </el-form-item>
          <el-form-item label="外部用户id" prop="userUnionId">
            <el-input v-model="taskFinishForm.userUnionId"></el-input>
          </el-form-item>
          <el-form-item label="是否完成" prop="feature">
            <el-radio-group v-model="taskFinishForm.feature">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="返回值" prop="value">
            <el-input v-model="taskFinishForm.value"></el-input>
          </el-form-item>
          <el-form-item label="额外信息" prop="attach">
            <el-input v-model="taskFinishForm.attach"></el-input>
          </el-form-item>
          <el-form-item label="完成时间" prop="finishTime">
            <el-input v-model="taskFinishForm.finishTime"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="submitTaskCenterForm" type="primary">请求</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="测试会员等级变化通知">
        <el-form :model="vipRankChangeForm">
          <el-form-item label="unionId" prop="unionId">
            <el-input v-model="vipRankChangeForm.unionId"></el-input>
          </el-form-item>
          <el-form-item label="gradleCode" prop="gradleCode">
            <el-input v-model="vipRankChangeForm.gradleCode"></el-input>
          </el-form-item>
          <el-form-item label="getGradleLastTime" prop="getGradleLastTime">
            <el-date-picker
                v-model="gradleLastTimeModel"
                type="datetime"
                placeholder="Select date and time"
            />
            {{vipRankChangeForm.getGradleLastTime}}
<!--            <el-input v-model="vipRankChangeForm.getGradleLastTime"></el-input>-->
          </el-form-item>
          <el-form-item>
            <el-button @click="submitVipRankForm" type="primary">请求</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="标签变更通知">
        <el-form :model="tagChangeForm">
          <el-form-item label="unionId">
            <el-input v-model="tagChangeForm.unionId"></el-input>
          </el-form-item>
          <el-form-item label="tagCode">
            <el-input v-model="tagChangeForm.tagCode"></el-input>
          </el-form-item>
          <el-form-item label="tagValue">
            <el-input v-model="tagChangeForm.tagValue"></el-input>
          </el-form-item>
          <el-form-item label="invalidTime">
            <el-date-picker
                v-model="invalidTimeModel"
                type="datetime"
                placeholder="Select date and time"
            />
            {{tagChangeForm.invalidTime}}
          </el-form-item>
          <el-form-item label="actionTypeEnum">
            <el-select v-model="tagChangeForm.actionTypeEnum">
              <el-option label="生成GENERATE" value="GENERATE"></el-option>
              <el-option label="覆盖COVER" value="COVER"></el-option>
              <el-option label="累加CUMULATIVE" value="CUMULATIVE"></el-option>
              <el-option label="累减SUBTRACT" value="SUBTRACT"></el-option>
            </el-select>
            {{tagChangeForm.actionTypeEnum}}
          </el-form-item>
          <el-form-item>
            <el-button @click="submitTabChangeForm" type="primary">请求</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="用户获取积分">
        <el-form :model="pointsDistributionForm">
          <el-form-item label="uniqueKey">
            <el-input v-model="pointsDistributionForm.uniqueKey"></el-input>
          </el-form-item>
          <el-form-item label="unionId">
            <el-input v-model="pointsDistributionForm.unionId"></el-input>
          </el-form-item>
          <el-form-item label="amount">
            <el-input v-model="pointsDistributionForm.amount"></el-input>
          </el-form-item>
          <el-form-item label="remark">
            <el-input v-model="pointsDistributionForm.remark"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="submitPointsDistributionForm" type="primary">请求</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="用户消费积分">
        <el-form :model="pointsReceiveForm">
          <el-form-item label="uniqueKey">
            <el-input v-model="pointsReceiveForm.uniqueKey"></el-input>
          </el-form-item>
          <el-form-item label="unionId">
            <el-input v-model="pointsReceiveForm.unionId"></el-input>
          </el-form-item>
          <el-form-item label="amount">
            <el-input v-model="pointsReceiveForm.amount"></el-input>
          </el-form-item>
          <el-form-item label="remark">
            <el-input v-model="pointsReceiveForm.remark"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="submitPointsReceiveForm" type="primary">请求</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
<!--    <h4> API URL: /api/reach/open/merchant/system/json</h4>-->
    <h4> 请求参数: </h4>
    <p> {{apiData}}</p>
    <h4> 请求结果: </h4>
    <p>{{ apiResult }}</p>
  </div>
</template>

<script setup>
import {nanoid} from "nanoid";
import CryptoJS from "crypto-js";
import {request,post} from "@/utils/request";

const activeName = ref('')
const handleClick = (e) => {
  // console.log('tab click e', e)
  apiData.value = ''
  apiResult.value = ''
}

const apiPath = ref('reach/open/merchant/system/json')

const secret = reactive({
  'app_id': 'a4qqw74gsrzt22',
  'app_secret': 'k9ytos1o7720cc41', // MD5
  'aes_key': '46dap1e3xdmf8mkp', // AES
})

const initOuterForm = ({action = ''}) => {
  return {
    timestamp: +new Date(),
    serialNumber: nanoid(),
    appId: secret.app_id,
    action,
    body: '', // getAESEncryptedBody
    // sign: ''
  }
}

const getAESEncryptedBody = (form) => {
  const key = CryptoJS.enc.Utf8.parse(secret.aes_key);
  const encryptedForm = CryptoJS.AES.encrypt(JSON.stringify(form), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encryptedForm.toString()
}

const getSign = ({outerForm}) => {
  const keys = Object.keys(outerForm)
  keys.sort()
  let str = '';
  keys.forEach(k => {
    str = str + k + '=' + outerForm[k] + '&'
  })
  str += 'appSecret=' + secret.app_secret

  console.log('str', str)
  const md5Str = CryptoJS.MD5(str).toString()
  return md5Str.toUpperCase()
}

const encryptedRequest = (url, data, options) => {
  console.log('url ===>', url)
  console.log('raw form ===>', data)
  console.log('action ===>', options.action)
  apiData.value = JSON.stringify(data)
  const outerForm = initOuterForm({action: options.action})
  outerForm.body = getAESEncryptedBody(data)
  outerForm.sign = getSign({outerForm})
  console.log('outer form ===>', outerForm)
  return request(url, outerForm)
}

const apiData = ref('')
const apiResult = ref('')

// 测试任务完成通知
const initTaskFinishForm = () => {
  return {
    taskCode: '',
    userUnionId: '',
    feature: 0,
    value: '',
    attach: '',
    finishTime: '',
  }
}
const taskFinishForm = reactive(initTaskFinishForm())
const submitTaskCenterForm = async () => {
  const rs = await encryptedRequest(apiPath.value, taskFinishForm, {action: 'task_advise'})
  apiResult.value = JSON.stringify(rs)
}

// 标签变更通知
const initTagChangeForm = () => {
  return {
    unionId: '',
    tagCode: '',
    tagValue: '',
    invalidTime: '',
    actionTypeEnum: '',
  }
}
const tagChangeForm = reactive(initTagChangeForm())
const invalidTimeModel = ref()
watch(invalidTimeModel, (newValue) => {
  console.log(newValue)
  tagChangeForm.invalidTime = +new Date(newValue)
})
const submitTabChangeForm = async () => {
  const rs = await encryptedRequest(apiPath.value, tagChangeForm, {action: 'label_user'})
  apiResult.value = JSON.stringify(rs)
}

// 用户获取积分
const initPointsDistributionForm = () => {
  return {
    uniqueKey: '',
    unionId: '',
    amount: '',
    remark: ''
  }
}
const pointsDistributionForm = reactive(initPointsDistributionForm())
const submitPointsDistributionForm = async () => {
  const rs = await encryptedRequest(apiPath.value, pointsDistributionForm, {action: 'receive'})
  apiResult.value = JSON.stringify(rs)
}

// 用户消费积分
const initPointsReceiveForm = () => {
  return {
    uniqueKey: '',
    unionId: '',
    amount: '',
    remark: ''
  }
}
const pointsReceiveForm = reactive(initPointsReceiveForm())
const submitPointsReceiveForm = async () => {
  const rs = await encryptedRequest(apiPath.value, pointsReceiveForm, {action: 'consume'})
  apiResult.value = JSON.stringify(rs)
}

// 测试会员等级变化通知
const initVipRankChange = () => {
  return {
    unionId: '',
    gradleCode: '',
    getGradleLastTime: ''
  }
}
const vipRankChangeForm = reactive(initVipRankChange())
const gradleLastTimeModel = ref()
watch(gradleLastTimeModel, (newValue) => {
  vipRankChangeForm.getGradleLastTime = +new Date(newValue)
})
const submitVipRankForm = async () => {
  const rs = await encryptedRequest(apiPath.value, vipRankChangeForm, {action: 'user_gradle_change'})
  apiResult.value = JSON.stringify(rs)
}

</script>

<style scoped lang="scss">
.page-content {
  padding: 20px;
}
</style>
